<?php
require_once ($_SERVER["DOCUMENT_ROOT"] ."/include/config.php");
require_once ("include/check.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
		<script src="js/json.js" type='text/javascript'></script>
		<script src="js/jquery-ui.min.js" type="text/javascript"></script>
		<script src="js/jquery.editable.js" type="text/javascript"></script>
		<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>
		<script src="js/util_script.js" type='text/javascript'></script>
		<script src="js/colorpicker.js" type="text/javascript"></script>
		<link href="css/colorpicker.css" rel="stylesheet" type="text/css" />
		<link href="css/styles.css" rel="stylesheet" type="text/css" />
		<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
		<link href="css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
		<script type="text/javascript">
		var dict = null;
			$(document).ready(function() {
				bindColorPicker($(".colPick"), "#000000");
				$("button").button();
				$("#add-entity").click(function() {
					$(".delModule").css("display", "none");
					$("#dict-name").text($("#dict-select option:selected").text());
					$("#entity-value").val("");
					$("#entity-edit-form").dialog("open");
				});
				$("#dict-table").dataTable({
					"bPaginate" : false,
					"bLengthChange" : false,
					"bFilter" : true,
					//					"bSort" : false,
					"bInfo" : false,
					"bAutoWidth" : false,
					"bFilter" : false,
					"bInfo" : false,
					"fnCreatedRow" : dictRowBound,
					"oLanguage" : {
						"sEmptyTable" : "Нет элементов для отображения"
					},
					"aoColumns" : [{
						"sClass" : "ui-widget-content"
					}, {
						"sClass" : "ui-widget-content"
					}]
				});

				//$("#dict-select").combobox();
				$("#dict-select").change(bindDictionaries);

				$("#entity-edit-form").dialog({
					autoOpen : false,
					height : 170,
					width : 400,
					draggable : true,
					resizable : false,
					modal : true,
					title : "Новая запись",
					dialogClass : "no-close",
					buttons : {
						"Сохранить" : function() {
							saveEntity();
						},
						"Отмена" : function() {
							$(this).dialog("close");
						}
					},
				});

			});

			function bindDictionaries() {
				var oTable = $("#dict-table").dataTable();
				dict = $("#dict-select").val();
				var colDict = dict == 'colors';
				$("#newColor").css("display", colDict? "block" : "none");
				$("#entity-value").css("display", colDict? "none" : "block");
				if (dict != "") {
					$.ajax({
						url : "include/dict.php",
						type : 'POST',
						data : {
							"dict" : dict,
							"op" : "get"
						}
					}).done(function(response) {
						values = JSON.parse(response);
						oTable.fnClearTable();
						$.each(values, function(id, val) {
							if (colDict) {
								var colParts = val.split('#');
								oTable.fnAddData([val, null]);
							}
							else
								oTable.fnAddData([val, id]);
						});
						$("#col1").html(colDict ? 'Цвет' : 'Название');
						});
					$("#add-entity").css("display", "block");
				} else {
					oTable.fnClearTable();
					$("#add-entity").css("display", "none");
				}
			}

			function deleteEntry(dict, id) {
				if (confirm("Вы действительно хотите удалить запись?")) {
					$.ajax({
						url : "include/dict.php",
						type : 'POST',
						data : {
							"dict" : dict,
							"id" : id,
							"op" : "del"
						}
					}).done(function(msg) {
						bindDictionaries();
					});
				}
			}

			function dictRowBound(nRow, aData, iDataIndex) {
				
				if (dict == 'colors') {
					var colParts = aData[0].split("#");
					var onclick = "deleteEntry('" + dict + "', '" + aData[0] + "'); return false;";
					$("td:eq(0)", nRow).html("<div class='colPick' style='width:120px; height:12px; display:inline-block; background-color:#" + colParts[1] +"' />&nbsp;").
						append($("<input type='checkbox' " + (colParts[0] == '1' ? "checked='checked'" :"" ) +"' disabled='disabled' />")).append("&nbsp;Кольцо");
					$("td:eq(1)", nRow).html("<a href='javascript:void(0)' class='module-edit-link' onclick=\"" + onclick + "\" >Удалить</a>");
					return;
				}
				var onclick = "deleteEntry('" + dict + "', '" + aData[1] + "'); return false;";				
				$("td:eq(1)", nRow).html("<a href='javascript:void(0)' class='module-edit-link' onclick=\"" + onclick + "\" >Удалить</a>");
				$("td:eq(0)", nRow).editable({
					"callback" : function(data) {
						if (!data.content) return;
						var oTable = $("#dict-table").dataTable();
						var oldVal = oTable.fnGetData(data.$el.get(0));
						if (!confirm("Обновить запись?")) {
							$(data.$el).html(oldVal);
							return;
						}
						var aPos = oTable.fnGetPosition(data.$el.get(0));
						oTable.fnUpdate(data.content, aPos[0], aPos[1]);
						var save_data = oTable.fnGetData(aPos[0]);
						saveEntity(save_data[1], save_data[0]);
					}
				});
			}
			
			function saveColor() {
				var color = getCPColor($("#newColor .colPick"));
				var ring = $("#newColor input[type=checkbox]").is(":checked");
				var exists = false;
				$("#dict-table td:first-child").each(function () {
					if (rgb2hex($(".colPick", this).css("background-color")) == color && ring == $("input", this).is(":checked"))
					{
						exists = true;
						return false;
					}
				});
				if (exists) {
					alert ('Такой цвет уже есть в справочнике!');
					return;
				}
				$.ajax({
					url : "include/dict.php",
					type : 'POST',
					data : {
						"dict": "colors",
						"ring": (ring ? "1" : "0"),
						"color":color,
						"op" : "add_color"
					}
				}).done(function(msg) {
					$("#entity-edit-form").dialog("close");
					bindDictionaries();
				});
			}

			function saveEntity(id, title) {
				if (dict == 'colors') { 
					saveColor();
					return;
				}
				
				if (!id)
					id = guid();
				if (!title)
					title = $("#entity-value").val();
				$.ajax({
					url : "include/dict.php",
					type : 'POST',
					data : {
						"dict" : dict,
						"id" : id,
						"title" : title,
						"op" : "set"
					}
				}).done(function(msg) {
					$("#entity-edit-form").dialog("close");
					bindDictionaries();
				});
			}

		</script>
	</head>
	<body>

    <table width="100%">
        <tr><td width="15%" valign="top">

                <?php include ("include/menu.php"); ?>
            </td><td width="70%" align="center" valign="top">

		<div class="main">
			<select id="dict-select">
				<option value=""></option>
				<option value="support_type">Типы опор</option>
				<option value="cable_params">Параметры кабеля</option>
				<option value="colors">Цвета</option>
			</select>
			<table id="dict-table" width="100%">
				<thead>
					<tr>
						<th width="80%" id='col1'>Название</th>
						<th id='col2'></th>
					</tr>
				</thead>
			</table>
			<br/>
			<button id="add-entity" style="display:none">
				Добавить запись
			</button>
			<div id="entity-edit-form">
				<table cellpadding="10" cellspacing="10" id='dictTable'>
					<tr>
						<td width="30%"> Словарь:</td>
						<td><b><span id="dict-name"></span></b></td>
					</tr>
					<tr>
						<td> Значение: </td>
						<td>
						<input type='text' id='entity-value' />
						<div id='newColor' style='display:none'>
							<div class='colPick' style='width:100px; display:inline-block; height:12px; margin-right:5px;'></div>
							<input type='checkbox' />&nbsp;Кольцо
						</div>
						</td>
					</tr>
				</table>
			</div>
		</div>
            </td>
            <td width="15%"></td>
        </tr>
    </table>
	</body>
</html>